<?php

namespace App\Repositories;

use App\Models\WechatUserSession;
use App\Models\WechatUser;
use App\Models\ChannelManager;
use App\Models\ItemManager;
use InfyOm\Generator\Common\BaseRepository as iBaseRepository;

class WechatUserSessionRepository extends iBaseRepository
{
    /**
     * @var array
     */
    protected $fieldSearchable = [
        'session_id',
        'openid',
        'unionid',
        'session_key',
        'status'
    ];

    /**
     * Configure the Model
     **/
    public function model()
    {
        return WechatUserSession::class;
    }

    public function saveSession($sessionKey)
    {
        $attributes = [
            'session_key' => $sessionKey['session_key'],
            'session_id' => str_replace('.', '', uniqid(md5($sessionKey['session_key']).time(), true)),
            'openid' => $sessionKey['openid']
        ];

        if ( ! empty($sessionKey['unionid']))
        {
            $attributes['unionid'] = $sessionKey['unionid'];
            $session = parent::updateOrCreate(['unionid' => $sessionKey['unionid']], $attributes);
        }
        else
        {
            $session = parent::updateOrCreate(['openid' => $sessionKey['openid']], $attributes);
        }


        $session->manage_channel_id = 0;
        $session->manage_item_id = 0;
        if ($session)
        {
            if ($session->unionid)
            {
                $user = WechatUser::where('unionid', $session->unionid)->first();
            }
            else
            {
                $user = WechatUser::where('openid', $session->openid)->first();
            }

            if ($user)
            {
                $channelManager = ChannelManager::where('wechat_user_id', $user->id)->first();
                if ($channelManager)
                {
                    $session->manage_channel_id = $channelManager->channel_id;
                }

                $itemManager = ItemManager::where('wechat_user_id', $user->id)->first();
                if ($itemManager)
                {
                    $session->manage_item_id = $itemManager->item_id;
                }
            }
            else
            {
                $session->manage_channel_id = 0;
                $session->manage_item_id = 0;
            }
        }

        return $session;
    }
}
